package org.polar.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.polar.util.Logger;
import org.polar.util.Tools;

import android.content.Context;
import android.location.Location;
import android.location.LocationManager;

public class GoogleGears {
	public interface ILocationListener{
		public void onCallback(Location loc);
	}

	private ILocationListener locationListener;
	public void setLocationListener (ILocationListener listener){
		locationListener = listener;
	}
	private GoogleGears(){}
	private static GoogleGears instance;
	public static GoogleGears getInstance(){
		if(instance == null){
			instance = new GoogleGears();
		}
		return instance;
	} 
	List<WifiInfo> mWifiInfoList ;
	List<CellIDInfo> mCellIDList = new ArrayList<CellIDInfo>();
	
	public void getMyLocation(Context mContext){
		WifiInfoManager wifiInfoManager = new WifiInfoManager();
		List<WifiInfo> wifiInfoList = wifiInfoManager.getWifiInfo(mContext);
 
		CellIDInfoManager cellIDInfoManager = new CellIDInfoManager();
		List<CellIDInfo> cellIDList =cellIDInfoManager.getCellIDInfo(mContext); 
		GoogleGears.getInstance().getMyLocation(wifiInfoList, cellIDList);
	}
	public void getMyLocation(List<WifiInfo> wifiInfoList,List<CellIDInfo> cellIDList) {
		this.mWifiInfoList = wifiInfoList;
		this.mCellIDList = cellIDList;
		Thread thread = new Thread(new Runnable(){
			@Override
			public void run() {
				Location loc = callGear(mWifiInfoList,mCellIDList);
				if(locationListener == null){
					return;
				}
				locationListener.onCallback(loc);
			}});
		thread.start();
	}

	private Location callGear(List<WifiInfo> wifi, List<CellIDInfo> cellID) {

		if ((cellID == null || cellID.size() == 0)
				&& (wifi == null || wifi.size() == 0)) {
			return null;
		}

		DefaultHttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost("http://www.google.com/loc/json");
		JSONObject holder = new JSONObject();
		try {
			holder.put("version", "1.1.0");
			holder.put("host", "maps.google.com");

			JSONObject data, current_data;
			JSONArray array = new JSONArray();
			
			if(cellID != null && cellID.size() > 0){
				holder.put("home_mobile_country_code", cellID.get(0)
						.getMobileCountryCode());
				holder.put("home_mobile_network_code", cellID.get(0)
						.getMobileNetworkCode());
				holder.put("radio_type", cellID.get(0).getRadioType());
				holder.put("request_address", true);
				if ("460".equals(cellID.get(0).getMobileCountryCode()))
					holder.put("address_language", "zh_CN");
				else
					holder.put("address_language", "en_US");
	
	
				current_data = new JSONObject();
				current_data.put("cell_id", cellID.get(0).getCellId());
				current_data.put("mobile_country_code", cellID.get(0)
						.getMobileCountryCode());
				current_data.put("mobile_network_code", cellID.get(0)
						.getMobileNetworkCode());
				current_data.put("age", 0);
				array.put(current_data);
	
				if (cellID.size() > 2) {
					for (int i = 1; i < cellID.size(); i++) {
						data = new JSONObject();
						data.put("cell_id", cellID.get(i).getCellId());
						data.put("location_area_code", cellID.get(0)
								.getLocationAreaCode());
						data.put("mobile_country_code", cellID.get(0)
								.getMobileCountryCode());
						data.put("mobile_network_code", cellID.get(0)
								.getMobileNetworkCode());
						data.put("age", 0);
						array.put(data);
					}
				}
				holder.put("cell_towers", array);
			}
			if (wifi != null && wifi.size() > 0 && wifi.get(0).getMac() != null) {
				data = new JSONObject();
				data.put("mac_address", wifi.get(0).getMac());
				data.put("signal_strength", 8);
				data.put("age", 0);
				array = new JSONArray();
				array.put(data);
				holder.put("wifi_towers", array);
			}

			StringEntity se = new StringEntity(holder.toString());
			Logger.d("Location send", holder.toString());
			post.setEntity(se);
			HttpResponse resp = client.execute(post);
			HttpEntity entity = resp.getEntity();
			BufferedReader br = new BufferedReader(new InputStreamReader(entity
					.getContent()));
			StringBuffer sb = new StringBuffer();
			String result = br.readLine();
			while (result != null) {
				Logger.d("Locaiton reseive", result);
				sb.append(result);
				result = br.readLine();
			}
			data = new JSONObject(sb.toString());
			data = (JSONObject) data.get("location");
			Location loc = new Location(LocationManager.NETWORK_PROVIDER);
			loc.setLatitude((Double) data.get("latitude"));
			loc.setLongitude((Double) data.get("longitude"));
			loc.setAccuracy(Float.parseFloat(data.get("accuracy").toString()));
			loc.setTime(Tools.getUTCTime());
			return loc;
		} catch (JSONException e) {
			return null;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}
